home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Python / import.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  55.8 KB  |  2,471 lines

  1. /* Module definition and import implementation */
  2.  
  3. #include "Python.h"
  4.  
  5. #include "node.h"
  6. #include "token.h"
  7. #include "errcode.h"
  8. #include "marshal.h"
  9. #include "compile.h"
  10. #include "eval.h"
  11. #include "osdefs.h"
  12. #include "importdl.h"
  13. #ifdef macintosh
  14. #include "macglue.h"
  15. #endif
  16. #include "protos/import.h"
  17. #include "protos/getmtime.h"
  18.  
  19. #ifdef HAVE_UNISTD_H
  20. #include <unistd.h>
  21. #endif
  22.  
  23. /* We expect that stat exists on most systems.
  24.    It's confirmed on Unix, Mac and Windows.
  25.    If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
  26. #ifndef DONT_HAVE_STAT
  27. #define HAVE_STAT
  28.  
  29. #ifndef DONT_HAVE_SYS_TYPES_H
  30. #include <sys/types.h>
  31. #endif
  32. #ifndef DONT_HAVE_SYS_STAT_H
  33. #include <sys/stat.h>
  34. #endif
  35.  
  36. #ifdef _AMIGA
  37. #include <proto/dos.h>
  38. #endif
  39.  
  40. #if defined(PYCC_VACPP)
  41. /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
  42. #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
  43. #endif
  44.  
  45. #ifndef S_ISDIR
  46. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  47. #endif
  48.  
  49. #endif
  50.  
  51.  
  52. extern long PyOS_GetLastModificationTime(); /* In getmtime.c */
  53.  
  54. /* Magic word to reject .pyc files generated by other Python versions */
  55. /* Change for each incompatible change */
  56. /* The value of CR and LF is incorporated so if you ever read or write
  57.    a .pyc file in text mode the magic number will be wrong; also, the
  58.    Apple MPW compiler swaps their values, botching string constants */
  59. /* XXX Perhaps the magic number should be frozen and a version field
  60.    added to the .pyc file header? */
  61. /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
  62. #define MAGIC (50428 | ((long)'\r'<<16) | ((long)'\n'<<24))
  63.  
  64. /* Magic word as global; note that _PyImport_Init() can change the
  65.    value of this global to accomodate for alterations of how the
  66.    compiler works which are enabled by command line switches. */
  67. static long pyc_magic = MAGIC;
  68.  
  69. /* See _PyImport_FixupExtension() below */
  70. static PyObject *extensions = NULL;
  71.  
  72. /* This table is defined in config.c: */
  73. extern struct _inittab _PyImport_Inittab[];
  74.  
  75. struct _inittab *PyImport_Inittab = _PyImport_Inittab;
  76.  
  77. /* these tables define the module suffixes that Python recognizes */
  78. struct filedescr * _PyImport_Filetab = NULL;
  79. static const struct filedescr _PyImport_StandardFiletab[] = {
  80.     {".py", "r", PY_SOURCE},
  81.     {".pyc", "rb", PY_COMPILED},
  82.     {0, 0}
  83. };
  84.  
  85. /* Initialize things */
  86.  
  87. void
  88. _PyImport_Init()
  89. {
  90.     const struct filedescr *scan;
  91.     struct filedescr *filetab;
  92.     int countD = 0;
  93.     int countS = 0;
  94.  
  95.     /* prepare _PyImport_Filetab: copy entries from
  96.        _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
  97.      */
  98.     for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
  99.         ++countD;
  100.     for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
  101.         ++countS;
  102.     filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
  103.     memcpy(filetab, _PyImport_DynLoadFiletab,
  104.            countD * sizeof(struct filedescr));
  105.     memcpy(filetab + countD, _PyImport_StandardFiletab,
  106.            countS * sizeof(struct filedescr));
  107.     filetab[countD + countS].suffix = NULL;
  108.  
  109.     _PyImport_Filetab = filetab;
  110.  
  111.     if (Py_OptimizeFlag) {
  112.         /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
  113.         for (; filetab->suffix != NULL; filetab++) {
  114.             if (strcmp(filetab->suffix, ".pyc") == 0)
  115.                 filetab->suffix = ".pyo";
  116.         }
  117.     }
  118.  
  119.     if (Py_UnicodeFlag) {
  120.         /* Fix the pyc_magic so that byte compiled code created
  121.            using the all-Unicode method doesn't interfere with
  122.            code created in normal operation mode. */
  123.         pyc_magic = MAGIC + 1;
  124.     }
  125. }
  126.  
  127. void
  128. _PyImport_Fini()
  129. {
  130.     Py_XDECREF(extensions);
  131.     extensions = NULL;
  132. }
  133.  
  134.  
  135. /* Locking primitives to prevent parallel imports of the same module
  136.    in different threads to return with a partially loaded module.
  137.    These calls are serialized by the global interpreter lock. */
  138.  
  139. #ifdef WITH_THREAD
  140.  
  141. #include "pythread.h"
  142.  
  143. static PyThread_type_lock import_lock = 0;
  144. static long import_lock_thread = -1;
  145. static int import_lock_level = 0;
  146.  
  147. static void
  148. lock_import()
  149. {
  150.     long me = PyThread_get_thread_ident();
  151.     if (me == -1)
  152.         return; /* Too bad */
  153.     if (import_lock == NULL)
  154.         import_lock = PyThread_allocate_lock();
  155.     if (import_lock_thread == me) {
  156.         import_lock_level++;
  157.         return;
  158.     }
  159.     if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
  160.         PyThreadState *tstate = PyEval_SaveThread();
  161.         PyThread_acquire_lock(import_lock, 1);
  162.         PyEval_RestoreThread(tstate);
  163.     }
  164.     import_lock_thread = me;
  165.     import_lock_level = 1;
  166. }
  167.  
  168. static void
  169. unlock_import()
  170. {
  171.     long me = PyThread_get_thread_ident();
  172.     if (me == -1)
  173.         return; /* Too bad */
  174.     if (import_lock_thread != me)
  175.         Py_FatalError("unlock_import: not holding the import lock");
  176.     import_lock_level--;
  177.     if (import_lock_level == 0) {
  178.         import_lock_thread = -1;
  179.         PyThread_release_lock(import_lock);
  180.     }
  181. }
  182.  
  183. #else
  184.  
  185. #define lock_import()
  186. #define unlock_import()
  187.  
  188. #endif
  189.  
  190. /* Helper for sys */
  191.  
  192. PyObject *
  193. PyImport_GetModuleDict()
  194. {
  195.     PyInterpreterState *interp = PyThreadState_Get()->interp;
  196.     if (interp->modules == NULL)
  197.         Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
  198.     return interp->modules;
  199. }
  200.  
  201.  
  202. /* List of names to clear in sys */
  203. static char* sys_deletes[] = {
  204.     "path", "argv", "ps1", "ps2", "exitfunc",
  205.     "exc_type", "exc_value", "exc_traceback",
  206.     "last_type", "last_value", "last_traceback",
  207.     NULL
  208. };
  209.  
  210. static char* sys_files[] = {
  211.     "stdin", "__stdin__",
  212.     "stdout", "__stdout__",
  213.     "stderr", "__stderr__",
  214.     NULL
  215. };
  216.  
  217.  
  218. /* Un-initialize things, as good as we can */
  219.  
  220. void
  221. PyImport_Cleanup()
  222. {
  223.     int pos, ndone;
  224.     char *name;
  225.     PyObject *key, *value, *dict;
  226.     PyInterpreterState *interp = PyThreadState_Get()->interp;
  227.     PyObject *modules = interp->modules;
  228.  
  229.     if (modules == NULL)
  230.         return; /* Already done */
  231.  
  232.     /* Delete some special variables first.  These are common
  233.        places where user values hide and people complain when their
  234.        destructors fail.  Since the modules containing them are
  235.        deleted *last* of all, they would come too late in the normal
  236.        destruction order.  Sigh. */
  237.  
  238.     value = PyDict_GetItemString(modules, "__builtin__");
  239.     if (value != NULL && PyModule_Check(value)) {
  240.         dict = PyModule_GetDict(value);
  241.         if (Py_VerboseFlag)
  242.             PySys_WriteStderr("# clear __builtin__._\n");
  243.         PyDict_SetItemString(dict, "_", Py_None);
  244.     }
  245.     value = PyDict_GetItemString(modules, "sys");
  246.     if (value != NULL && PyModule_Check(value)) {
  247.         char **p;
  248.         PyObject *v;
  249.         dict = PyModule_GetDict(value);
  250.         for (p = sys_deletes; *p != NULL; p++) {
  251.             if (Py_VerboseFlag)
  252.                 PySys_WriteStderr("# clear sys.%s\n", *p);
  253.             PyDict_SetItemString(dict, *p, Py_None);
  254.         }
  255.         for (p = sys_files; *p != NULL; p+=2) {
  256.             if (Py_VerboseFlag)
  257.                 PySys_WriteStderr("# restore sys.%s\n", *p);
  258.             v = PyDict_GetItemString(dict, *(p+1));
  259.             if (v == NULL)
  260.                 v = Py_None;
  261.             PyDict_SetItemString(dict, *p, v);
  262.         }
  263.     }
  264.  
  265.     /* First, delete __main__ */
  266.     value = PyDict_GetItemString(modules, "__main__");
  267.     if (value != NULL && PyModule_Check(value)) {
  268.         if (Py_VerboseFlag)
  269.             PySys_WriteStderr("# cleanup __main__\n");
  270.         _PyModule_Clear(value);
  271.         PyDict_SetItemString(modules, "__main__", Py_None);
  272.     }
  273.  
  274.     /* The special treatment of __builtin__ here is because even
  275.        when it's not referenced as a module, its dictionary is
  276.        referenced by almost every module's __builtins__.  Since
  277.        deleting a module clears its dictionary (even if there are
  278.        references left to it), we need to delete the __builtin__
  279.        module last.  Likewise, we don't delete sys until the very
  280.        end because it is implicitly referenced (e.g. by print).
  281.  
  282.        Also note that we 'delete' modules by replacing their entry
  283.        in the modules dict with None, rather than really deleting
  284.        them; this avoids a rehash of the modules dictionary and
  285.        also marks them as "non existent" so they won't be
  286.        re-imported. */
  287.  
  288.     /* Next, repeatedly delete modules with a reference count of
  289.        one (skipping __builtin__ and sys) and delete them */
  290.     do {
  291.         ndone = 0;
  292.         pos = 0;
  293.         while (PyDict_Next(modules, &pos, &key, &value)) {
  294.             if (value->ob_refcnt != 1)
  295.                 continue;
  296.             if (PyString_Check(key) && PyModule_Check(value)) {
  297.                 name = PyString_AS_STRING(key);
  298.                 if (strcmp(name, "__builtin__") == 0)
  299.                     continue;
  300.                 if (strcmp(name, "sys") == 0)
  301.                     continue;
  302.                 if (Py_VerboseFlag)
  303.                     PySys_WriteStderr(
  304.                         "# cleanup[1] %s\n", name);
  305.                 _PyModule_Clear(value);
  306.                 PyDict_SetItem(modules, key, Py_None);
  307.                 ndone++;
  308.             }
  309.         }
  310.     } while (ndone > 0);
  311.  
  312.     /* Next, delete all modules (still skipping __builtin__ and sys) */
  313.     pos = 0;
  314.     while (PyDict_Next(modules, &pos, &key, &value)) {
  315.         if (PyString_Check(key) && PyModule_Check(value)) {
  316.             name = PyString_AS_STRING(key);
  317.             if (strcmp(name, "__builtin__") == 0)
  318.                 continue;
  319.             if (strcmp(name, "sys") == 0)
  320.                 continue;
  321.             if (Py_VerboseFlag)
  322.                 PySys_WriteStderr("# cleanup[2] %s\n", name);
  323.             _PyModule_Clear(value);
  324.             PyDict_SetItem(modules, key, Py_None);
  325.         }
  326.     }
  327.  
  328.     /* Next, delete sys and __builtin__ (in that order) */
  329.     value = PyDict_GetItemString(modules, "sys");
  330.     if (value != NULL && PyModule_Check(value)) {
  331.         if (Py_VerboseFlag)
  332.             PySys_WriteStderr("# cleanup sys\n");
  333.         _PyModule_Clear(value);
  334.         PyDict_SetItemString(modules, "sys", Py_None);
  335.     }
  336.     value = PyDict_GetItemString(modules, "__builtin__");
  337.     if (value != NULL && PyModule_Check(value)) {
  338.         if (Py_VerboseFlag)
  339.             PySys_WriteStderr("# cleanup __builtin__\n");
  340.         _PyModule_Clear(value);
  341.         PyDict_SetItemString(modules, "__builtin__", Py_None);
  342.     }
  343.  
  344.     /* Finally, clear and delete the modules directory */
  345.     PyDict_Clear(modules);
  346.     interp->modules = NULL;
  347.     Py_DECREF(modules);
  348. }
  349.  
  350.  
  351. /* Helper for pythonrun.c -- return magic number */
  352.  
  353. long
  354. PyImport_GetMagicNumber()
  355. {
  356.     return pyc_magic;
  357. }
  358.  
  359.  
  360. /* Magic for extension modules (built-in as well as dynamically
  361.    loaded).  To prevent initializing an extension module more than
  362.    once, we keep a static dictionary 'extensions' keyed by module name
  363.    (for built-in modules) or by filename (for dynamically loaded
  364.    modules), containing these modules.  A copy od the module's
  365.    dictionary is stored by calling _PyImport_FixupExtension()
  366.    immediately after the module initialization function succeeds.  A
  367.    copy can be retrieved from there by calling
  368.    _PyImport_FindExtension(). */
  369.  
  370. PyObject *
  371. _PyImport_FixupExtension(name, filename)
  372.     char *name;
  373.     char *filename;
  374. {
  375.     PyObject *modules, *mod, *dict, *copy;
  376.     if (extensions == NULL) {
  377.         extensions = PyDict_New();
  378.         if (extensions == NULL)
  379.             return NULL;
  380.     }
  381.     modules = PyImport_GetModuleDict();
  382.     mod = PyDict_GetItemString(modules, name);
  383.     if (mod == NULL || !PyModule_Check(mod)) {
  384.         PyErr_Format(PyExc_SystemError,
  385.           "_PyImport_FixupExtension: module %.200s not loaded", name);
  386.         return NULL;
  387.     }
  388.     dict = PyModule_GetDict(mod);
  389.     if (dict == NULL)
  390.         return NULL;
  391.     copy = PyObject_CallMethod(dict, "copy", "");
  392.     if (copy == NULL)
  393.         return NULL;
  394.     PyDict_SetItemString(extensions, filename, copy);
  395.     Py_DECREF(copy);
  396.     return copy;
  397. }
  398.  
  399. PyObject *
  400. _PyImport_FindExtension(name, filename)
  401.     char *name;
  402.     char *filename;
  403. {
  404.     PyObject *dict, *mod, *mdict, *result;
  405.     if (extensions == NULL)
  406.         return NULL;
  407.     dict = PyDict_GetItemString(extensions, filename);
  408.     if (dict == NULL)
  409.         return NULL;
  410.     mod = PyImport_AddModule(name);
  411.     if (mod == NULL)
  412.         return NULL;
  413.     mdict = PyModule_GetDict(mod);
  414.     if (mdict == NULL)
  415.         return NULL;
  416.     result = PyObject_CallMethod(mdict, "update", "O", dict);
  417.     if (result == NULL)
  418.         return NULL;
  419.     Py_DECREF(result);
  420.     if (Py_VerboseFlag)
  421.         PySys_WriteStderr("import %s # previously loaded (%s)\n",
  422.             name, filename);
  423.     return mod;
  424. }
  425.  
  426.  
  427. /* Get the module object corresponding to a module name.
  428.    First check the modules dictionary if there's one there,
  429.    if not, create a new one and insert in in the modules dictionary.
  430.    Because the former action is most common, THIS DOES NOT RETURN A
  431.    'NEW' REFERENCE! */
  432.  
  433. PyObject *
  434. PyImport_AddModule(name)
  435.     char *name;
  436. {
  437.     PyObject *modules = PyImport_GetModuleDict();
  438.     PyObject *m;
  439.  
  440.     if ((m = PyDict_GetItemString(modules, name)) != NULL &&
  441.         PyModule_Check(m))
  442.         return m;
  443.     m = PyModule_New(name);
  444.     if (m == NULL)
  445.         return NULL;
  446.     if (PyDict_SetItemString(modules, name, m) != 0) {
  447.         Py_DECREF(m);
  448.         return NULL;
  449.     }
  450.     Py_DECREF(m); /* Yes, it still exists, in modules! */
  451.  
  452.     return m;
  453. }
  454.  
  455.  
  456. /* Execute a code object in a module and return the module object
  457.    WITH INCREMENTED REFERENCE COUNT */
  458.  
  459. PyObject *
  460. PyImport_ExecCodeModule(name, co)
  461.     char *name;
  462.     PyObject *co;
  463. {
  464.     return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
  465. }
  466.  
  467. PyObject *
  468. PyImport_ExecCodeModuleEx(name, co, pathname)
  469.     char *name;
  470.     PyObject *co;
  471.     char *pathname;
  472. {
  473.     PyObject *modules = PyImport_GetModuleDict();
  474.     PyObject *m, *d, *v;
  475.  
  476.     m = PyImport_AddModule(name);
  477.     if (m == NULL)
  478.         return NULL;
  479.     d = PyModule_GetDict(m);
  480.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  481.         if (PyDict_SetItemString(d, "__builtins__",
  482.                      PyEval_GetBuiltins()) != 0)
  483.             return NULL;
  484.     }
  485.     /* Remember the filename as the __file__ attribute */
  486.     v = NULL;
  487.     if (pathname != NULL) {
  488.         v = PyString_FromString(pathname);
  489.         if (v == NULL)
  490.             PyErr_Clear();
  491.     }
  492.     if (v == NULL) {
  493.         v = ((PyCodeObject *)co)->co_filename;
  494.         Py_INCREF(v);
  495.     }
  496.     if (PyDict_SetItemString(d, "__file__", v) != 0)
  497.         PyErr_Clear(); /* Not important enough to report */
  498.     Py_DECREF(v);
  499.  
  500.     v = PyEval_EvalCode((PyCodeObject *)co, d, d);
  501.     if (v == NULL)
  502.         return NULL;
  503.     Py_DECREF(v);
  504.  
  505.     if ((m = PyDict_GetItemString(modules, name)) == NULL) {
  506.         PyErr_Format(PyExc_ImportError,
  507.                  "Loaded module %.200s not found in sys.modules",
  508.                  name);
  509.         return NULL;
  510.     }
  511.  
  512.     Py_INCREF(m);
  513.  
  514.     return m;
  515. }
  516.  
  517.  
  518. /* Given a pathname for a Python source file, fill a buffer with the
  519.    pathname for the corresponding compiled file.  Return the pathname
  520.    for the compiled file, or NULL if there's no space in the buffer.
  521.    Doesn't set an exception. */
  522.  
  523. static char *
  524. make_compiled_pathname(pathname, buf, buflen)
  525.     char *pathname;
  526.     char *buf;
  527.     int buflen;
  528. {
  529.     int len;
  530.  
  531.     len = strlen(pathname);
  532.     if (len+2 > buflen)
  533.         return NULL;
  534.     strcpy(buf, pathname);
  535.     strcpy(buf+len, Py_OptimizeFlag ? "o" : "c");
  536.  
  537.     return buf;
  538. }
  539.  
  540.  
  541. /* Given a pathname for a Python source file, its time of last
  542.    modification, and a pathname for a compiled file, check whether the
  543.    compiled file represents the same version of the source.  If so,
  544.    return a FILE pointer for the compiled file, positioned just after
  545.    the header; if not, return NULL.
  546.    Doesn't set an exception. */
  547.  
  548. static FILE *
  549. check_compiled_module(pathname, mtime, cpathname)
  550.     char *pathname;
  551.     long mtime;
  552.     char *cpathname;
  553. {
  554.     FILE *fp;
  555.     long magic;
  556.     long pyc_mtime;
  557.  
  558.     fp = fopen(cpathname, "rb");
  559.     if (fp == NULL)
  560.         return NULL;
  561.     magic = PyMarshal_ReadLongFromFile(fp);
  562.     if (magic != pyc_magic) {
  563.         if (Py_VerboseFlag)
  564.             PySys_WriteStderr("# %s has bad magic\n", cpathname);
  565.         fclose(fp);
  566.         return NULL;
  567.     }
  568.     pyc_mtime = PyMarshal_ReadLongFromFile(fp);
  569.     if (pyc_mtime != mtime) {
  570.         if (Py_VerboseFlag)
  571.             PySys_WriteStderr("# %s has bad mtime\n", cpathname);
  572.         fclose(fp);
  573.         return NULL;
  574.     }
  575.     if (Py_VerboseFlag)
  576.         PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
  577.     return fp;
  578. }
  579.  
  580.  
  581. /* Read a code object from a file and check it for validity */
  582.  
  583. static PyCodeObject *
  584. read_compiled_module(cpathname, fp)
  585.     char *cpathname;
  586.     FILE *fp;
  587. {
  588.     PyObject *co;
  589.  
  590.     co = PyMarshal_ReadObjectFromFile(fp);
  591.     /* Ugly: rd_object() may return NULL with or without error */
  592.     if (co == NULL || !PyCode_Check(co)) {
  593.         if (!PyErr_Occurred())
  594.             PyErr_Format(PyExc_ImportError,
  595.                 "Non-code object in %.200s", cpathname);
  596.         Py_XDECREF(co);
  597.         return NULL;
  598.     }
  599.     return (PyCodeObject *)co;
  600. }
  601.  
  602.  
  603. /* Load a module from a compiled file, execute it, and return its
  604.    module object WITH INCREMENTED REFERENCE COUNT */
  605.  
  606. static PyObject *
  607. load_compiled_module(name, cpathname, fp)
  608.     char *name;
  609.     char *cpathname;
  610.     FILE *fp;
  611. {
  612.     long magic;
  613.     PyCodeObject *co;
  614.     PyObject *m;
  615.  
  616.     magic = PyMarshal_ReadLongFromFile(fp);
  617.     if (magic != pyc_magic) {
  618.         PyErr_Format(PyExc_ImportError,
  619.                  "Bad magic number in %.200s", cpathname);
  620.         return NULL;
  621.     }
  622.     (void) PyMarshal_ReadLongFromFile(fp);
  623.     co = read_compiled_module(cpathname, fp);
  624.     if (co == NULL)
  625.         return NULL;
  626.     if (Py_VerboseFlag)
  627.         PySys_WriteStderr("import %s # precompiled from %s\n",
  628.             name, cpathname);
  629.     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
  630.     Py_DECREF(co);
  631.  
  632.     return m;
  633. }
  634.  
  635. /* Parse a source file and return the corresponding code object */
  636.  
  637. static PyCodeObject *
  638. parse_source_module(pathname, fp)
  639.     char *pathname;
  640.     FILE *fp;
  641. {
  642.     PyCodeObject *co;
  643.     node *n;
  644.  
  645.     n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
  646.     if (n == NULL)
  647.         return NULL;
  648.     co = PyNode_Compile(n, pathname);
  649.     PyNode_Free(n);
  650.  
  651.     return co;
  652. }
  653.  
  654.  
  655. /* Write a compiled module to a file, placing the time of last
  656.    modification of its source into the header.
  657.    Errors are ignored, if a write error occurs an attempt is made to
  658.    remove the file. */
  659.  
  660. static void
  661. write_compiled_module(co, cpathname, mtime)
  662.     PyCodeObject *co;
  663.     char *cpathname;
  664.     long mtime;
  665. {
  666.     FILE *fp;
  667.  
  668.     fp = fopen(cpathname, "wb");
  669.     if (fp == NULL) {
  670.         if (Py_VerboseFlag)
  671.             PySys_WriteStderr(
  672.                 "# can't create %s\n", cpathname);
  673.         return;
  674.     }
  675.     PyMarshal_WriteLongToFile(pyc_magic, fp);
  676.     /* First write a 0 for mtime */
  677.     PyMarshal_WriteLongToFile(0L, fp);
  678.     PyMarshal_WriteObjectToFile((PyObject *)co, fp);
  679.     if (ferror(fp)) {
  680.         if (Py_VerboseFlag)
  681.             PySys_WriteStderr("# can't write %s\n", cpathname);
  682.         /* Don't keep partial file */
  683.         fclose(fp);
  684.         (void) unlink(cpathname);
  685.         return;
  686.     }
  687.     /* Now write the true mtime */
  688.     fseek(fp, 4L, 0);
  689.     PyMarshal_WriteLongToFile(mtime, fp);
  690.     fflush(fp);
  691.     fclose(fp);
  692.     if (Py_VerboseFlag)
  693.         PySys_WriteStderr("# wrote %s\n", cpathname);
  694. #ifdef macintosh
  695.     setfiletype(cpathname, 'Pyth', 'PYC ');
  696. #endif
  697. }
  698.  
  699.  
  700. /* Load a source module from a given file and return its module
  701.    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
  702.    byte-compiled file, use that instead. */
  703.  
  704. static PyObject *
  705. load_source_module(name, pathname, fp)
  706.     char *name;
  707.     char *pathname;
  708.     FILE *fp;
  709. {
  710.     long mtime;
  711.     FILE *fpc;
  712.     char buf[MAXPATHLEN+1];
  713.     char *cpathname;
  714.     PyCodeObject *co;
  715.     PyObject *m;
  716.  
  717.     mtime = PyOS_GetLastModificationTime(pathname, fp);
  718.     cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
  719.     if (cpathname != NULL &&
  720.         (fpc = check_compiled_module(pathname, mtime, cpathname))) {
  721.         co = read_compiled_module(cpathname, fpc);
  722.         fclose(fpc);
  723.         if (co == NULL)
  724.             return NULL;
  725.         if (Py_VerboseFlag)
  726.             PySys_WriteStderr("import %s # precompiled from %s\n",
  727.                 name, cpathname);
  728.         pathname = cpathname;
  729.     }
  730.     else {
  731.         co = parse_source_module(pathname, fp);
  732.         if (co == NULL)
  733.             return NULL;
  734.         if (Py_VerboseFlag)
  735.             PySys_WriteStderr("import %s # from %s\n",
  736.                 name, pathname);
  737.         write_compiled_module(co, cpathname, mtime);
  738.     }
  739.     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
  740.     Py_DECREF(co);
  741.  
  742.     return m;
  743. }
  744.  
  745.  
  746. /* Forward */
  747. static PyObject *load_module Py_PROTO((char *, FILE *, char *, int));
  748. static struct filedescr *find_module Py_PROTO((char *, PyObject *,
  749.                            char *, int, FILE **));
  750. static struct _frozen *find_frozen Py_PROTO((char *name));
  751.  
  752. /* Load a package and return its module object WITH INCREMENTED
  753.    REFERENCE COUNT */
  754.  
  755. static PyObject *
  756. load_package(name, pathname)
  757.     char *name;
  758.     char *pathname;
  759. {
  760.     PyObject *m, *d, *file, *path;
  761.     int err;
  762.     char buf[MAXPATHLEN+1];
  763.     FILE *fp = NULL;
  764.     struct filedescr *fdp;
  765.  
  766.     m = PyImport_AddModule(name);
  767.     if (m == NULL)
  768.         return NULL;
  769.     if (Py_VerboseFlag)
  770.         PySys_WriteStderr("import %s # directory %s\n",
  771.             name, pathname);
  772.     d = PyModule_GetDict(m);
  773.     file = PyString_FromString(pathname);
  774.     if (file == NULL)
  775.         return NULL;
  776.     path = Py_BuildValue("[O]", file);
  777.     if (path == NULL) {
  778.         Py_DECREF(file);
  779.         return NULL;
  780.     }
  781.     err = PyDict_SetItemString(d, "__file__", file);
  782.     if (err == 0)
  783.         err = PyDict_SetItemString(d, "__path__", path);
  784.     if (err != 0) {
  785.         m = NULL;
  786.         goto cleanup;
  787.     }
  788.     buf[0] = '\0';
  789.     fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
  790.     if (fdp == NULL) {
  791.         if (PyErr_ExceptionMatches(PyExc_ImportError)) {
  792.             PyErr_Clear();
  793.         }
  794.         else
  795.             m = NULL;
  796.         goto cleanup;
  797.     }
  798.     m = load_module(name, fp, buf, fdp->type);
  799.     if (fp != NULL)
  800.         fclose(fp);
  801.   cleanup:
  802.     Py_XDECREF(path);
  803.     Py_XDECREF(file);
  804.     return m;
  805. }
  806.  
  807.  
  808. /* Helper to test for built-in module */
  809.  
  810. static int
  811. is_builtin(name)
  812.     char *name;
  813. {
  814.     int i;
  815.     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  816.         if (strcmp(name, PyImport_Inittab[i].name) == 0) {
  817.             if (PyImport_Inittab[i].initfunc == NULL)
  818.                 return -1;
  819.             else
  820.                 return 1;
  821.         }
  822.     }
  823.     return 0;
  824. }
  825.  
  826.  
  827. /* Search the path (default sys.path) for a module.  Return the
  828.    corresponding filedescr struct, and (via return arguments) the
  829.    pathname and an open file.  Return NULL if the module is not found. */
  830.  
  831. #ifdef MS_COREDLL
  832. extern FILE *PyWin_FindRegisteredModule();
  833. #endif
  834.  
  835. #ifdef CHECK_IMPORT_CASE
  836. static int check_case(char *, int, int, char *);
  837. #endif
  838.  
  839. static int find_init_module Py_PROTO((char *)); /* Forward */
  840.  
  841. static struct filedescr *
  842. find_module(realname, path, buf, buflen, p_fp)
  843.     char *realname;
  844.     PyObject *path;
  845.     /* Output parameters: */
  846.     char *buf;
  847.     int buflen;
  848.     FILE **p_fp;
  849. {
  850.     int i, npath, len, namelen;
  851.     struct _frozen *f;
  852.     struct filedescr *fdp = NULL;
  853.     FILE *fp = NULL;
  854.     struct stat statbuf;
  855.     static struct filedescr fd_frozen = {"", "", PY_FROZEN};
  856.     static struct filedescr fd_builtin = {"", "", C_BUILTIN};
  857.     static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
  858.     char name[MAXPATHLEN+1];
  859.  
  860.     strcpy(name, realname);
  861.  
  862.     if (path != NULL && PyString_Check(path)) {
  863.         /* Submodule of "frozen" package:
  864.            Set name to the fullname, path to NULL
  865.            and continue as "usual" */
  866.         if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
  867.             PyErr_SetString(PyExc_ImportError,
  868.                     "full frozen module name too long");
  869.             return NULL;
  870.         }
  871.         strcpy(buf, PyString_AsString(path));
  872.         strcat(buf, ".");
  873.         strcat(buf, name);
  874.         strcpy(name, buf);
  875.         path = NULL;
  876.     }
  877.     if (path == NULL) {
  878.         if (is_builtin(name)) {
  879.             strcpy(buf, name);
  880.             return &fd_builtin;
  881.         }
  882.         if ((f = find_frozen(name)) != NULL) {
  883.             strcpy(buf, name);
  884.             return &fd_frozen;
  885.         }
  886.  
  887. #ifdef MS_COREDLL
  888.         fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
  889.         if (fp != NULL) {
  890.             *p_fp = fp;
  891.             return fdp;
  892.         }
  893. #endif
  894.         path = PySys_GetObject("path");
  895.     }
  896.     if (path == NULL || !PyList_Check(path)) {
  897.         PyErr_SetString(PyExc_ImportError,
  898.                 "sys.path must be a list of directory names");
  899.         return NULL;
  900.     }
  901.     npath = PyList_Size(path);
  902.     namelen = strlen(name);
  903.     for (i = 0; i < npath; i++) {
  904.         PyObject *v = PyList_GetItem(path, i);
  905.         if (!PyString_Check(v))
  906.             continue;
  907.         len = PyString_Size(v);
  908.         if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
  909.             continue; /* Too long */
  910.         strcpy(buf, PyString_AsString(v));
  911.         if ((int)strlen(buf) != len)
  912.             continue; /* v contains '\0' */
  913. #ifdef macintosh
  914. #ifdef INTERN_STRINGS
  915.         /* 
  916.         ** Speedup: each sys.path item is interned, and
  917.         ** FindResourceModule remembers which items refer to
  918.         ** folders (so we don't have to bother trying to look
  919.         ** into them for resources). 
  920.         */
  921.         PyString_InternInPlace(&PyList_GET_ITEM(path, i));
  922.         v = PyList_GET_ITEM(path, i);
  923. #endif
  924.         if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
  925.             static struct filedescr resfiledescr =
  926.                 {"", "", PY_RESOURCE};
  927.             
  928.             return &resfiledescr;
  929.         }
  930.         if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
  931.             static struct filedescr resfiledescr =
  932.                 {"", "", PY_CODERESOURCE};
  933.             
  934.             return &resfiledescr;
  935.         }
  936. #endif
  937. #ifdef _AMIGA
  938.         /* Use the dos.library to construct the pathname */
  939.         AddPart(buf,name,MAXPATHLEN);
  940.         len=strlen(buf);
  941. #else /* !_AMIGA */
  942.         if (len > 0 && buf[len-1] != SEP
  943. #ifdef ALTSEP
  944.             && buf[len-1] != ALTSEP
  945. #endif
  946.             )
  947.             buf[len++] = SEP;
  948. #ifdef IMPORT_8x3_NAMES
  949.         /* see if we are searching in directory dos-8x3 */
  950.         if (len > 7 && !strncmp(buf + len - 8, "dos-8x3", 7)){
  951.             int j;
  952.             char ch;  /* limit name to 8 lower-case characters */
  953.             for (j = 0; (ch = name[j]) && j < 8; j++)
  954.                 if (isupper(ch))
  955.                     buf[len++] = tolower(ch);
  956.                 else
  957.                     buf[len++] = ch;
  958.         }
  959.         else /* Not in dos-8x3, use the full name */
  960. #endif
  961.         {
  962.             strcpy(buf+len, name);
  963.             len += namelen;
  964.         }
  965. #endif /* !_AMIGA */
  966. #ifdef HAVE_STAT
  967.         if (stat(buf, &statbuf) == 0) {
  968.             if (S_ISDIR(statbuf.st_mode)) {
  969.                 if (find_init_module(buf)) {
  970. #ifdef CHECK_IMPORT_CASE
  971.                     if (!check_case(buf, len, namelen,
  972.                             name))
  973.                         return NULL;
  974. #endif
  975.                     return &fd_package;
  976.                 }
  977.             }
  978.         }
  979. #else
  980.         /* XXX How are you going to test for directories? */
  981. #endif
  982. #ifdef macintosh
  983.         fdp = PyMac_FindModuleExtension(buf, &len, name);
  984.         if (fdp)
  985.             fp = fopen(buf, fdp->mode);
  986. #else
  987.         for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  988.             strcpy(buf+len, fdp->suffix);
  989.             if (Py_VerboseFlag > 1)
  990.                 PySys_WriteStderr("# trying %s\n", buf);
  991.             fp = fopen(buf, fdp->mode);
  992.             if (fp != NULL)
  993.                 break;
  994.         }
  995. #endif /* !macintosh */
  996.         if (fp != NULL)
  997.             break;
  998.     }
  999.     if (fp == NULL) {
  1000.         PyErr_Format(PyExc_ImportError,
  1001.                  "No module named %.200s", name);
  1002.         return NULL;
  1003.     }
  1004. #ifdef CHECK_IMPORT_CASE
  1005.     if (!check_case(buf, len, namelen, name)) {
  1006.         fclose(fp);
  1007.         return NULL;
  1008.     }
  1009. #endif
  1010.  
  1011.     *p_fp = fp;
  1012.     return fdp;
  1013. }
  1014.  
  1015. #ifdef CHECK_IMPORT_CASE
  1016.  
  1017. #ifdef MS_WIN32
  1018. #include <windows.h>
  1019. #include <ctype.h>
  1020.  
  1021. static int
  1022. allcaps8x3(s)
  1023.     char *s;
  1024. {
  1025.     /* Return 1 if s is an 8.3 filename in ALLCAPS */
  1026.     char c;
  1027.     char *dot = strchr(s, '.');
  1028.     char *end = strchr(s, '\0');
  1029.     if (dot != NULL) {
  1030.         if (dot-s > 8)
  1031.             return 0; /* More than 8 before '.' */
  1032.         if (end-dot > 4)
  1033.             return 0; /* More than 3 after '.' */
  1034.         end = strchr(dot+1, '.');
  1035.         if (end != NULL)
  1036.             return 0; /* More than one dot  */
  1037.     }
  1038.     else if (end-s > 8)
  1039.         return 0; /* More than 8 and no dot */
  1040.     while ((c = *s++)) {
  1041.         if (islower(c))
  1042.             return 0;
  1043.     }
  1044.     return 1;
  1045. }
  1046.  
  1047. static int
  1048. check_case(char *buf, int len, int namelen, char *name)
  1049. {
  1050.     WIN32_FIND_DATA data;
  1051.     HANDLE h;
  1052.     if (getenv("PYTHONCASEOK") != NULL)
  1053.         return 1;
  1054.     h = FindFirstFile(buf, &data);
  1055.     if (h == INVALID_HANDLE_VALUE) {
  1056.         PyErr_Format(PyExc_NameError,
  1057.           "Can't find file for module %.100s\n(filename %.300s)",
  1058.           name, buf);
  1059.         return 0;
  1060.     }
  1061.     FindClose(h);
  1062.     if (allcaps8x3(data.cFileName)) {
  1063.         /* Skip the test if the filename is ALL.CAPS.  This can
  1064.            happen in certain circumstances beyond our control,
  1065.            e.g. when software is installed under NT on a FAT
  1066.            filesystem and then the same FAT filesystem is used
  1067.            under Windows 95. */
  1068.         return 1;
  1069.     }
  1070.     if (strncmp(data.cFileName, name, namelen) != 0) {
  1071.         strcpy(buf+len-namelen, data.cFileName);
  1072.         PyErr_Format(PyExc_NameError,
  1073.           "Case mismatch for module name %.100s\n(filename %.300s)",
  1074.           name, buf);
  1075.         return 0;
  1076.     }
  1077.     return 1;
  1078. }
  1079. #endif /* MS_WIN32 */
  1080.  
  1081. #ifdef macintosh
  1082. #include <TextUtils.h>
  1083. #ifdef USE_GUSI1
  1084. #include "TFileSpec.h"        /* for Path2FSSpec() */
  1085. #endif
  1086. static int
  1087. check_case(char *buf, int len, int namelen, char *name)
  1088. {
  1089.     FSSpec fss;
  1090.     OSErr err;
  1091. #ifndef USE_GUSI1
  1092.     err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
  1093. #else
  1094.     /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
  1095.        the way, which is fine for all directories, but here we need
  1096.        the original name of the alias file (say, Dlg.ppc.slb, not
  1097.        toolboxmodules.ppc.slb). */
  1098.     char *colon;
  1099.     err = Path2FSSpec(buf, &fss);
  1100.     if (err == noErr) {
  1101.         colon = strrchr(buf, ':'); /* find filename */
  1102.         if (colon != NULL)
  1103.             err = FSMakeFSSpec(fss.vRefNum, fss.parID,
  1104.                        Pstring(colon+1), &fss);
  1105.         else
  1106.             err = FSMakeFSSpec(fss.vRefNum, fss.parID,
  1107.                        fss.name, &fss);
  1108.     }
  1109. #endif
  1110.     if (err) {
  1111.         PyErr_Format(PyExc_NameError,
  1112.              "Can't find file for module %.100s\n(filename %.300s)",
  1113.              name, buf);
  1114.         return 0;
  1115.     }
  1116.     p2cstr(fss.name);
  1117.     if ( strncmp(name, (char *)fss.name, namelen) != 0 ) {
  1118.         PyErr_Format(PyExc_NameError,
  1119.              "Case mismatch for module name %.100s\n(filename %.300s)",
  1120.              name, fss.name);
  1121.         return 0;
  1122.     }
  1123.     return 1;
  1124. }
  1125. #endif /* macintosh */
  1126.  
  1127. #ifdef DJGPP
  1128. #include <dir.h>
  1129.  
  1130. static int
  1131. check_case(char *buf, int len, int namelen, char *name)
  1132. {
  1133.     struct ffblk ffblk;
  1134.     int done;
  1135.  
  1136.     if (getenv("PYTHONCASEOK") != NULL)
  1137.         return 1;
  1138.     done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
  1139.     if (done) {
  1140.         PyErr_Format(PyExc_NameError,
  1141.           "Can't find file for module %.100s\n(filename %.300s)",
  1142.           name, buf);
  1143.         return 0;
  1144.     }
  1145.  
  1146.     if (strncmp(ffblk.ff_name, name, namelen) != 0) {
  1147.         strcpy(buf+len-namelen, ffblk.ff_name);
  1148.         PyErr_Format(PyExc_NameError,
  1149.           "Case mismatch for module name %.100s\n(filename %.300s)",
  1150.           name, buf);
  1151.         return 0;
  1152.     }
  1153.     return 1;
  1154. }
  1155. #endif
  1156.  
  1157. #ifdef _AMIGA
  1158. static int
  1159. check_case(char *buf, int len, int namelen, char *name)
  1160. {
  1161.     BPTR lock;
  1162.     struct FileInfoBlock __aligned fib;
  1163.     char tmpbuf[200];
  1164.  
  1165.     if(GetVar("PYTHONCASEOK",tmpbuf,200,NULL)>=0)
  1166.         return 1;
  1167.  
  1168.     if(lock=Lock(buf,ACCESS_READ))
  1169.     {
  1170.         if(Examine(lock,&fib))
  1171.         {
  1172.             UnLock(lock);
  1173.             if (strncmp(fib.fib_FileName, name, namelen) != 0)
  1174.             {
  1175.                 strcpy(buf+len-namelen, fib.fib_FileName);
  1176.                 PyErr_Format(PyExc_NameError,
  1177.                   "Case mismatch for module name %.100s\n(filename %.300s)",
  1178.                   name, buf);
  1179.                 return 0;
  1180.             }
  1181.             return 1;
  1182.         }
  1183.         UnLock(lock);
  1184.     }
  1185.     PyErr_Format(PyExc_NameError,
  1186.       "Can't find file for module %.100s\n(filename %.300s)",
  1187.       name, buf);
  1188.     return 0;
  1189. }
  1190. #endif /* _AMIGA */
  1191.  
  1192. #endif /* CHECK_IMPORT_CASE */
  1193.  
  1194. #ifdef HAVE_STAT
  1195. /* Helper to look for __init__.py or __init__.py[co] in potential package */
  1196. static int
  1197. find_init_module(buf)
  1198.     char *buf;
  1199. {
  1200.     int save_len = strlen(buf);
  1201.     int i = save_len;
  1202.     struct stat statbuf;
  1203.  
  1204.     if (save_len + 13 >= MAXPATHLEN)
  1205.         return 0;
  1206.     buf[i++] = SEP;
  1207.     strcpy(buf+i, "__init__.py");
  1208.     if (stat(buf, &statbuf) == 0) {
  1209.         buf[save_len] = '\0';
  1210.         return 1;
  1211.     }
  1212.     i += strlen(buf+i);
  1213.     if (Py_OptimizeFlag)
  1214.         strcpy(buf+i, "o");
  1215.     else
  1216.         strcpy(buf+i, "c");
  1217.     if (stat(buf, &statbuf) == 0) {
  1218.         buf[save_len] = '\0';
  1219.         return 1;
  1220.     }
  1221.     buf[save_len] = '\0';
  1222.     return 0;
  1223. }
  1224. #endif /* HAVE_STAT */
  1225.  
  1226.  
  1227. static int init_builtin Py_PROTO((char *)); /* Forward */
  1228.  
  1229. /* Load an external module using the default search path and return
  1230.    its module object WITH INCREMENTED REFERENCE COUNT */
  1231.  
  1232. static PyObject *
  1233. load_module(name, fp, buf, type)
  1234.     char *name;
  1235.     FILE *fp;
  1236.     char *buf;
  1237.     int type;
  1238. {
  1239.     PyObject *modules;
  1240.     PyObject *m;
  1241.     int err;
  1242.  
  1243.     /* First check that there's an open file (if we need one)  */
  1244.     switch (type) {
  1245.     case PY_SOURCE:
  1246.     case PY_COMPILED:
  1247.         if (fp == NULL) {
  1248.             PyErr_Format(PyExc_ValueError,
  1249.                "file object required for import (type code %d)",
  1250.                      type);
  1251.             return NULL;
  1252.         }
  1253.     }
  1254.  
  1255.     switch (type) {
  1256.  
  1257.     case PY_SOURCE:
  1258.         m = load_source_module(name, buf, fp);
  1259.         break;
  1260.  
  1261.     case PY_COMPILED:
  1262.         m = load_compiled_module(name, buf, fp);
  1263.         break;
  1264.  
  1265. #ifdef HAVE_DYNAMIC_LOADING
  1266.     case C_EXTENSION:
  1267.         m = _PyImport_LoadDynamicModule(name, buf, fp);
  1268.         break;
  1269. #endif
  1270.  
  1271. #ifdef macintosh
  1272.     case PY_RESOURCE:
  1273.         m = PyMac_LoadResourceModule(name, buf);
  1274.         break;
  1275.     case PY_CODERESOURCE:
  1276.         m = PyMac_LoadCodeResourceModule(name, buf);
  1277.         break;
  1278. #endif
  1279.  
  1280.     case PKG_DIRECTORY:
  1281.         m = load_package(name, buf);
  1282.         break;
  1283.  
  1284.     case C_BUILTIN:
  1285.     case PY_FROZEN:
  1286.         if (buf != NULL && buf[0] != '\0')
  1287.             name = buf;
  1288.         if (type == C_BUILTIN)
  1289.             err = init_builtin(name);
  1290.         else
  1291.             err = PyImport_ImportFrozenModule(name);
  1292.         if (err < 0)
  1293.             return NULL;
  1294.         if (err == 0) {
  1295.             PyErr_Format(PyExc_ImportError,
  1296.                      "Purported %s module %.200s not found",
  1297.                      type == C_BUILTIN ?
  1298.                         "builtin" : "frozen",
  1299.                      name);
  1300.             return NULL;
  1301.         }
  1302.         modules = PyImport_GetModuleDict();
  1303.         m = PyDict_GetItemString(modules, name);
  1304.         if (m == NULL) {
  1305.             PyErr_Format(
  1306.                 PyExc_ImportError,
  1307.                 "%s module %.200s not properly initialized",
  1308.                 type == C_BUILTIN ?
  1309.                     "builtin" : "frozen",
  1310.                 name);
  1311.             return NULL;
  1312.         }
  1313.         Py_INCREF(m);
  1314.         break;
  1315.  
  1316.     default:
  1317.         PyErr_Format(PyExc_ImportError,
  1318.                  "Don't know how to import %.200s (type code %d)",
  1319.                   name, type);
  1320.         m = NULL;
  1321.  
  1322.     }
  1323.  
  1324.     return m;
  1325. }
  1326.  
  1327.  
  1328. /* Initialize a built-in module.
  1329.    Return 1 for succes, 0 if the module is not found, and -1 with
  1330.    an exception set if the initialization failed. */
  1331.  
  1332. static int
  1333. init_builtin(name)
  1334.     char *name;
  1335. {
  1336.     struct _inittab *p;
  1337.     PyObject *mod;
  1338.  
  1339.     if ((mod = _PyImport_FindExtension(name, name)) != NULL)
  1340.         return 1;
  1341.  
  1342.     for (p = PyImport_Inittab; p->name != NULL; p++) {
  1343.         if (strcmp(name, p->name) == 0) {
  1344.             if (p->initfunc == NULL) {
  1345.                 PyErr_Format(PyExc_ImportError,
  1346.                     "Cannot re-init internal module %.200s",
  1347.                     name);
  1348.                 return -1;
  1349.             }
  1350.             if (Py_VerboseFlag)
  1351.                 PySys_WriteStderr("import %s # builtin\n", name);
  1352.             (*p->initfunc)();
  1353.             if (PyErr_Occurred())
  1354.                 return -1;
  1355.             if (_PyImport_FixupExtension(name, name) == NULL)
  1356.                 return -1;
  1357.             return 1;
  1358.         }
  1359.     }
  1360.     return 0;
  1361. }
  1362.  
  1363.  
  1364. /* Frozen modules */
  1365.  
  1366. static struct _frozen *
  1367. find_frozen(name)
  1368.     char *name;
  1369. {
  1370.     struct _frozen *p;
  1371.  
  1372.     for (p = PyImport_FrozenModules; ; p++) {
  1373.         if (p->name == NULL)
  1374.             return NULL;
  1375.         if (strcmp(p->name, name) == 0)
  1376.             break;
  1377.     }
  1378.     return p;
  1379. }
  1380.  
  1381. static PyObject *
  1382. get_frozen_object(name)
  1383.     char *name;
  1384. {
  1385.     struct _frozen *p = find_frozen(name);
  1386.     int size;
  1387.  
  1388.     if (p == NULL) {
  1389.         PyErr_Format(PyExc_ImportError,
  1390.                  "No such frozen object named %.200s",
  1391.                  name);
  1392.         return NULL;
  1393.     }
  1394.     size = p->size;
  1395.     if (size < 0)
  1396.         size = -size;
  1397.     return PyMarshal_ReadObjectFromString((char *)p->code, size);
  1398. }
  1399.  
  1400. /* Initialize a frozen module.
  1401.    Return 1 for succes, 0 if the module is not found, and -1 with
  1402.    an exception set if the initialization failed.
  1403.    This function is also used from frozenmain.c */
  1404.  
  1405. int
  1406. PyImport_ImportFrozenModule(name)
  1407.     char *name;
  1408. {
  1409.     struct _frozen *p = find_frozen(name);
  1410.     PyObject *co;
  1411.     PyObject *m;
  1412.     int ispackage;
  1413.     int size;
  1414.  
  1415.     if (p == NULL)
  1416.         return 0;
  1417.     size = p->size;
  1418.     ispackage = (size < 0);
  1419.     if (ispackage)
  1420.         size = -size;
  1421.     if (Py_VerboseFlag)
  1422.         PySys_WriteStderr("import %s # frozen%s\n",
  1423.             name, ispackage ? " package" : "");
  1424.     co = PyMarshal_ReadObjectFromString((char *)p->code, size);
  1425.     if (co == NULL)
  1426.         return -1;
  1427.     if (!PyCode_Check(co)) {
  1428.         Py_DECREF(co);
  1429.         PyErr_Format(PyExc_TypeError,
  1430.                  "frozen object %.200s is not a code object",
  1431.                  name);
  1432.         return -1;
  1433.     }
  1434.     if (ispackage) {
  1435.         /* Set __path__ to the package name */
  1436.         PyObject *d, *s;
  1437.         int err;
  1438.         m = PyImport_AddModule(name);
  1439.         if (m == NULL)
  1440.             return -1;
  1441.         d = PyModule_GetDict(m);
  1442.         s = PyString_InternFromString(name);
  1443.         if (s == NULL)
  1444.             return -1;
  1445.         err = PyDict_SetItemString(d, "__path__", s);
  1446.         Py_DECREF(s);
  1447.         if (err != 0)
  1448.             return err;
  1449.     }
  1450.     m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
  1451.     Py_DECREF(co);
  1452.     if (m == NULL)
  1453.         return -1;
  1454.     Py_DECREF(m);
  1455.     return 1;
  1456. }
  1457.  
  1458.  
  1459. /* Import a module, either built-in, frozen, or external, and return
  1460.    its module object WITH INCREMENTED REFERENCE COUNT */
  1461.  
  1462. PyObject *
  1463. PyImport_ImportModule(name)
  1464.     char *name;
  1465. {
  1466.     static PyObject *fromlist = NULL;
  1467.     if (fromlist == NULL && strchr(name, '.') != NULL) {
  1468.         fromlist = Py_BuildValue("[s]", "*");
  1469.         if (fromlist == NULL)
  1470.             return NULL;
  1471.     }
  1472.     return PyImport_ImportModuleEx(name, NULL, NULL, fromlist);
  1473. }
  1474.  
  1475. /* Forward declarations for helper routines */
  1476. static PyObject *get_parent Py_PROTO((PyObject *globals,
  1477.                       char *buf, int *p_buflen));
  1478. static PyObject *load_next Py_PROTO((PyObject *mod, PyObject *altmod,
  1479.                      char **p_name, char *buf, int *p_buflen));
  1480. static int mark_miss Py_PROTO((char *name));
  1481. static int ensure_fromlist Py_PROTO((PyObject *mod, PyObject *fromlist,
  1482.                      char *buf, int buflen, int recursive));
  1483. static PyObject * import_submodule Py_PROTO((PyObject *mod,
  1484.                          char *name, char *fullname));
  1485.  
  1486. /* The Magnum Opus of dotted-name import :-) */
  1487.  
  1488. static PyObject *
  1489. import_module_ex(name, globals, locals, fromlist)
  1490.     char *name;
  1491.     PyObject *globals;
  1492.     PyObject *locals;
  1493.     PyObject *fromlist;
  1494. {
  1495.     char buf[MAXPATHLEN+1];
  1496.     int buflen = 0;
  1497.     PyObject *parent, *head, *next, *tail;
  1498.  
  1499.     parent = get_parent(globals, buf, &buflen);
  1500.     if (parent == NULL)
  1501.         return NULL;
  1502.  
  1503.     head = load_next(parent, Py_None, &name, buf, &buflen);
  1504.     if (head == NULL)
  1505.         return NULL;
  1506.  
  1507.     tail = head;
  1508.     Py_INCREF(tail);
  1509.     while (name) {
  1510.         next = load_next(tail, tail, &name, buf, &buflen);
  1511.         Py_DECREF(tail);
  1512.         if (next == NULL) {
  1513.             Py_DECREF(head);
  1514.             return NULL;
  1515.         }
  1516.         tail = next;
  1517.     }
  1518.  
  1519.     if (fromlist != NULL) {
  1520.         if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
  1521.             fromlist = NULL;
  1522.     }
  1523.  
  1524.     if (fromlist == NULL) {
  1525.         Py_DECREF(tail);
  1526.         return head;
  1527.     }
  1528.  
  1529.     Py_DECREF(head);
  1530.     if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
  1531.         Py_DECREF(tail);
  1532.         return NULL;
  1533.     }
  1534.  
  1535.     return tail;
  1536. }
  1537.  
  1538. PyObject *
  1539. PyImport_ImportModuleEx(name, globals, locals, fromlist)
  1540.     char *name;
  1541.     PyObject *globals;
  1542.     PyObject *locals;
  1543.     PyObject *fromlist;
  1544. {
  1545.     PyObject *result;
  1546.     lock_import();
  1547.     result = import_module_ex(name, globals, locals, fromlist);
  1548.     unlock_import();
  1549.     return result;
  1550. }
  1551.  
  1552. static PyObject *
  1553. get_parent(globals, buf, p_buflen)
  1554.     PyObject *globals;
  1555.     char *buf;
  1556.     int *p_buflen;
  1557. {
  1558.     static PyObject *namestr = NULL;
  1559.     static PyObject *pathstr = NULL;
  1560.     PyObject *modname, *modpath, *modules, *parent;
  1561.  
  1562.     if (globals == NULL || !PyDict_Check(globals))
  1563.         return Py_None;
  1564.  
  1565.     if (namestr == NULL) {
  1566.         namestr = PyString_InternFromString("__name__");
  1567.         if (namestr == NULL)
  1568.             return NULL;
  1569.     }
  1570.     if (pathstr == NULL) {
  1571.         pathstr = PyString_InternFromString("__path__");
  1572.         if (pathstr == NULL)
  1573.             return NULL;
  1574.     }
  1575.  
  1576.     *buf = '\0';
  1577.     *p_buflen = 0;
  1578.     modname = PyDict_GetItem(globals, namestr);
  1579.     if (modname == NULL || !PyString_Check(modname))
  1580.         return Py_None;
  1581.  
  1582.     modpath = PyDict_GetItem(globals, pathstr);
  1583.     if (modpath != NULL) {
  1584.         int len = PyString_GET_SIZE(modname);
  1585.         if (len > MAXPATHLEN) {
  1586.             PyErr_SetString(PyExc_ValueError,
  1587.                     "Module name too long");
  1588.             return NULL;
  1589.         }
  1590.         strcpy(buf, PyString_AS_STRING(modname));
  1591.         *p_buflen = len;
  1592.     }
  1593.     else {
  1594.         char *start = PyString_AS_STRING(modname);
  1595.         char *lastdot = strrchr(start, '.');
  1596.         int len;
  1597.         if (lastdot == NULL)
  1598.             return Py_None;
  1599.         len = lastdot - start;
  1600.         if (len >= MAXPATHLEN) {
  1601.             PyErr_SetString(PyExc_ValueError,
  1602.                     "Module name too long");
  1603.             return NULL;
  1604.         }
  1605.         strncpy(buf, start, len);
  1606.         buf[len] = '\0';
  1607.         *p_buflen = len;
  1608.     }
  1609.  
  1610.     modules = PyImport_GetModuleDict();
  1611.     parent = PyDict_GetItemString(modules, buf);
  1612.     if (parent == NULL)
  1613.         parent = Py_None;
  1614.     return parent;
  1615.     /* We expect, but can't guarantee, if parent != None, that:
  1616.        - parent.__name__ == buf
  1617.        - parent.__dict__ is globals
  1618.        If this is violated...  Who cares? */
  1619. }
  1620.  
  1621. static PyObject *
  1622. load_next(mod, altmod, p_name, buf, p_buflen)
  1623.     PyObject *mod;
  1624.     PyObject *altmod; /* Either None or same as mod */
  1625.     char **p_name;
  1626.     char *buf;
  1627.     int *p_buflen;
  1628. {
  1629.     char *name = *p_name;
  1630.     char *dot = strchr(name, '.');
  1631.     int len;
  1632.     char *p;
  1633.     PyObject *result;
  1634.  
  1635.     if (dot == NULL) {
  1636.         *p_name = NULL;
  1637.         len = strlen(name);
  1638.     }
  1639.     else {
  1640.         *p_name = dot+1;
  1641.         len = dot-name;
  1642.     }
  1643.     if (len == 0) {
  1644.         PyErr_SetString(PyExc_ValueError,
  1645.                 "Empty module name");
  1646.         return NULL;
  1647.     }
  1648.  
  1649.     p = buf + *p_buflen;
  1650.     if (p != buf)
  1651.         *p++ = '.';
  1652.     if (p+len-buf >= MAXPATHLEN) {
  1653.         PyErr_SetString(PyExc_ValueError,
  1654.                 "Module name too long");
  1655.         return NULL;
  1656.     }
  1657.     strncpy(p, name, len);
  1658.     p[len] = '\0';
  1659.     *p_buflen = p+len-buf;
  1660.  
  1661.     result = import_submodule(mod, p, buf);
  1662.     if (result == Py_None && altmod != mod) {
  1663.         Py_DECREF(result);
  1664.         /* Here, altmod must be None and mod must not be None */
  1665.         result = import_submodule(altmod, p, p);
  1666.         if (result != NULL && result != Py_None) {
  1667.             if (mark_miss(buf) != 0) {
  1668.                 Py_DECREF(result);
  1669.                 return NULL;
  1670.             }
  1671.             strncpy(buf, name, len);
  1672.             buf[len] = '\0';
  1673.             *p_buflen = len;
  1674.         }
  1675.     }
  1676.     if (result == NULL)
  1677.         return NULL;
  1678.  
  1679.     if (result == Py_None) {
  1680.         Py_DECREF(result);
  1681.         PyErr_Format(PyExc_ImportError,
  1682.                  "No module named %.200s", name);
  1683.         return NULL;
  1684.     }
  1685.  
  1686.     return result;
  1687. }
  1688.  
  1689. static int
  1690. mark_miss(name)
  1691.     char *name;
  1692. {
  1693.     PyObject *modules = PyImport_GetModuleDict();
  1694.     return PyDict_SetItemString(modules, name, Py_None);
  1695. }
  1696.  
  1697. static int
  1698. ensure_fromlist(mod, fromlist, buf, buflen, recursive)
  1699.     PyObject *mod;
  1700.     PyObject *fromlist;
  1701.     char *buf;
  1702.     int buflen;
  1703.     int recursive;
  1704. {
  1705.     int i;
  1706.  
  1707.     if (!PyObject_HasAttrString(mod, "__path__"))
  1708.         return 1;
  1709.  
  1710.     for (i = 0; ; i++) {
  1711.         PyObject *item = PySequence_GetItem(fromlist, i);
  1712.         int hasit;
  1713.         if (item == NULL) {
  1714.             if (PyErr_ExceptionMatches(PyExc_IndexError)) {
  1715.                 PyErr_Clear();
  1716.                 return 1;
  1717.             }
  1718.             return 0;
  1719.         }
  1720.         if (!PyString_Check(item)) {
  1721.             PyErr_SetString(PyExc_TypeError,
  1722.                     "Item in ``from list'' not a string");
  1723.             Py_DECREF(item);
  1724.             return 0;
  1725.         }
  1726.         if (PyString_AS_STRING(item)[0] == '*') {
  1727.             PyObject *all;
  1728.             Py_DECREF(item);
  1729.             /* See if the package defines __all__ */
  1730.             if (recursive)
  1731.                 continue; /* Avoid endless recursion */
  1732.             all = PyObject_GetAttrString(mod, "__all__");
  1733.             if (all == NULL)
  1734.                 PyErr_Clear();
  1735.             else {
  1736.                 if (!ensure_fromlist(mod, all, buf, buflen, 1))
  1737.                     return 0;
  1738.                 Py_DECREF(all);
  1739.             }
  1740.             continue;
  1741.         }
  1742.         hasit = PyObject_HasAttr(mod, item);
  1743.         if (!hasit) {
  1744.             char *subname = PyString_AS_STRING(item);
  1745.             PyObject *submod;
  1746.             char *p;
  1747.             if (buflen + strlen(subname) >= MAXPATHLEN) {
  1748.                 PyErr_SetString(PyExc_ValueError,
  1749.                         "Module name too long");
  1750.                 Py_DECREF(item);
  1751.                 return 0;
  1752.             }
  1753.             p = buf + buflen;
  1754.             *p++ = '.';
  1755.             strcpy(p, subname);
  1756.             submod = import_submodule(mod, subname, buf);
  1757.             Py_XDECREF(submod);
  1758.             if (submod == NULL) {
  1759.                 Py_DECREF(item);
  1760.                 return 0;
  1761.             }
  1762.         }
  1763.         Py_DECREF(item);
  1764.     }
  1765.  
  1766.     /* NOTREACHED */
  1767. }
  1768.  
  1769. static PyObject *
  1770. import_submodule(mod, subname, fullname)
  1771.     PyObject *mod; /* May be None */
  1772.     char *subname;
  1773.     char *fullname;
  1774. {
  1775.     PyObject *modules = PyImport_GetModuleDict();
  1776.     PyObject *m;
  1777.  
  1778.     /* Require:
  1779.        if mod == None: subname == fullname
  1780.        else: mod.__name__ + "." + subname == fullname
  1781.     */
  1782.  
  1783.     if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { 
  1784.         Py_INCREF(m);
  1785.     }
  1786.     else {
  1787.         PyObject *path;
  1788.         char buf[MAXPATHLEN+1];
  1789.         struct filedescr *fdp;
  1790.         FILE *fp = NULL;
  1791.  
  1792.         if (mod == Py_None)
  1793.             path = NULL;
  1794.         else {
  1795.             path = PyObject_GetAttrString(mod, "__path__");
  1796.             if (path == NULL) {
  1797.                 PyErr_Clear();
  1798.                 Py_INCREF(Py_None);
  1799.                 return Py_None;
  1800.             }
  1801.         }
  1802.  
  1803.         buf[0] = '\0';
  1804.         fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
  1805.         Py_XDECREF(path);
  1806.         if (fdp == NULL) {
  1807.             if (!PyErr_ExceptionMatches(PyExc_ImportError))
  1808.                 return NULL;
  1809.             PyErr_Clear();
  1810.             Py_INCREF(Py_None);
  1811.             return Py_None;
  1812.         }
  1813.         m = load_module(fullname, fp, buf, fdp->type);
  1814.         if (fp)
  1815.             fclose(fp);
  1816.         if (m != NULL && mod != Py_None) {
  1817.             if (PyObject_SetAttrString(mod, subname, m) < 0) {
  1818.                 Py_DECREF(m);
  1819.                 m = NULL;
  1820.             }
  1821.         }
  1822.     }
  1823.  
  1824.     return m;
  1825. }
  1826.  
  1827.  
  1828. /* Re-import a module of any kind and return its module object, WITH
  1829.    INCREMENTED REFERENCE COUNT */
  1830.  
  1831. PyObject *
  1832. PyImport_ReloadModule(m)
  1833.     PyObject *m;
  1834. {
  1835.     PyObject *modules = PyImport_GetModuleDict();
  1836.     PyObject *path = NULL;
  1837.     char *name, *subname;
  1838.     char buf[MAXPATHLEN+1];
  1839.     struct filedescr *fdp;
  1840.     FILE *fp = NULL;
  1841.  
  1842.     if (m == NULL || !PyModule_Check(m)) {
  1843.         PyErr_SetString(PyExc_TypeError,
  1844.                 "reload() argument must be module");
  1845.         return NULL;
  1846.     }
  1847.     name = PyModule_GetName(m);
  1848.     if (name == NULL)
  1849.         return NULL;
  1850.     if (m != PyDict_GetItemString(modules, name)) {
  1851.         PyErr_Format(PyExc_ImportError,
  1852.                  "reload(): module %.200s not in sys.modules",
  1853.                  name);
  1854.         return NULL;
  1855.     }
  1856.     subname = strrchr(name, '.');
  1857.     if (subname == NULL)
  1858.         subname = name;
  1859.     else {
  1860.         PyObject *parentname, *parent;
  1861.         parentname = PyString_FromStringAndSize(name, (subname-name));
  1862.         if (parentname == NULL)
  1863.             return NULL;
  1864.         parent = PyDict_GetItem(modules, parentname);
  1865.         Py_DECREF(parentname);
  1866.         if (parent == NULL) {
  1867.             PyErr_Format(PyExc_ImportError,
  1868.                 "reload(): parent %.200s not in sys.modules",
  1869.                 name);
  1870.             return NULL;
  1871.         }
  1872.         subname++;
  1873.         path = PyObject_GetAttrString(parent, "__path__");
  1874.         if (path == NULL)
  1875.             PyErr_Clear();
  1876.     }
  1877.     buf[0] = '\0';
  1878.     fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
  1879.     Py_XDECREF(path);
  1880.     if (fdp == NULL)
  1881.         return NULL;
  1882.     m = load_module(name, fp, buf, fdp->type);
  1883.     if (fp)
  1884.         fclose(fp);
  1885.     return m;
  1886. }
  1887.  
  1888.  
  1889. /* Higher-level import emulator which emulates the "import" statement
  1890.    more accurately -- it invokes the __import__() function from the
  1891.    builtins of the current globals.  This means that the import is
  1892.    done using whatever import hooks are installed in the current
  1893.    environment, e.g. by "rexec".
  1894.    A dummy list ["__doc__"] is passed as the 4th argument so that
  1895.    e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
  1896.    will return <module "gencache"> instead of <module "win32com">. */
  1897.  
  1898. PyObject *
  1899. PyImport_Import(module_name)
  1900.     PyObject *module_name;
  1901. {
  1902.     static PyObject *silly_list = NULL;
  1903.     static PyObject *builtins_str = NULL;
  1904.     static PyObject *import_str = NULL;
  1905.     static PyObject *standard_builtins = NULL;
  1906.     PyObject *globals = NULL;
  1907.     PyObject *import = NULL;
  1908.     PyObject *builtins = NULL;
  1909.     PyObject *r = NULL;
  1910.  
  1911.     /* Initialize constant string objects */
  1912.     if (silly_list == NULL) {
  1913.         import_str = PyString_InternFromString("__import__");
  1914.         if (import_str == NULL)
  1915.             return NULL;
  1916.         builtins_str = PyString_InternFromString("__builtins__");
  1917.         if (builtins_str == NULL)
  1918.             return NULL;
  1919.         silly_list = Py_BuildValue("[s]", "__doc__");
  1920.         if (silly_list == NULL)
  1921.             return NULL;
  1922.     }
  1923.  
  1924.     /* Get the builtins from current globals */
  1925.     globals = PyEval_GetGlobals();
  1926.     if(globals != NULL) {
  1927.             Py_INCREF(globals);
  1928.         builtins = PyObject_GetItem(globals, builtins_str);
  1929.         if (builtins == NULL)
  1930.             goto err;
  1931.     }
  1932.     else {
  1933.         /* No globals -- use standard builtins, and fake globals */
  1934.         PyErr_Clear();
  1935.  
  1936.         if (standard_builtins == NULL) {
  1937.             standard_builtins =
  1938.                 PyImport_ImportModule("__builtin__");
  1939.             if (standard_builtins == NULL)
  1940.                 return NULL;
  1941.         }
  1942.  
  1943.         builtins = standard_builtins;
  1944.         Py_INCREF(builtins);
  1945.         globals = Py_BuildValue("{OO}", builtins_str, builtins);
  1946.         if (globals == NULL)
  1947.             goto err;
  1948.     }
  1949.  
  1950.     /* Get the __import__ function from the builtins */
  1951.     if (PyDict_Check(builtins))
  1952.         import=PyObject_GetItem(builtins, import_str);
  1953.     else
  1954.         import=PyObject_GetAttr(builtins, import_str);
  1955.     if (import == NULL)
  1956.         goto err;
  1957.  
  1958.     /* Call the _import__ function with the proper argument list */
  1959.     r = PyObject_CallFunction(import, "OOOO",
  1960.                   module_name, globals, globals, silly_list);
  1961.  
  1962.   err:
  1963.     Py_XDECREF(globals);
  1964.     Py_XDECREF(builtins);
  1965.     Py_XDECREF(import);
  1966.  
  1967.     return r;
  1968. }
  1969.  
  1970.  
  1971. /* Module 'imp' provides Python access to the primitives used for
  1972.    importing modules.
  1973. */
  1974.  
  1975. static PyObject *
  1976. imp_get_magic(self, args)
  1977.     PyObject *self;
  1978.     PyObject *args;
  1979. {
  1980.     char buf[4];
  1981.  
  1982.     if (!PyArg_ParseTuple(args, ":get_magic"))
  1983.         return NULL;
  1984.     buf[0] = (char) ((pyc_magic >>  0) & 0xff);
  1985.     buf[1] = (char) ((pyc_magic >>  8) & 0xff);
  1986.     buf[2] = (char) ((pyc_magic >> 16) & 0xff);
  1987.     buf[3] = (char) ((pyc_magic >> 24) & 0xff);
  1988.  
  1989.     return PyString_FromStringAndSize(buf, 4);
  1990. }
  1991.  
  1992. static PyObject *
  1993. imp_get_suffixes(self, args)
  1994.     PyObject *self;
  1995.     PyObject *args;
  1996. {
  1997.     PyObject *list;
  1998.     struct filedescr *fdp;
  1999.  
  2000.     if (!PyArg_ParseTuple(args, ":get_suffixes"))
  2001.         return NULL;
  2002.     list = PyList_New(0);
  2003.     if (list == NULL)
  2004.         return NULL;
  2005.     for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  2006.         PyObject *item = Py_BuildValue("ssi",
  2007.                        fdp->suffix, fdp->mode, fdp->type);
  2008.         if (item == NULL) {
  2009.             Py_DECREF(list);
  2010.             return NULL;
  2011.         }
  2012.         if (PyList_Append(list, item) < 0) {
  2013.             Py_DECREF(list);
  2014.             Py_DECREF(item);
  2015.             return NULL;
  2016.         }
  2017.         Py_DECREF(item);
  2018.     }
  2019.     return list;
  2020. }
  2021.  
  2022. static PyObject *
  2023. call_find_module(name, path)
  2024.     char *name;
  2025.     PyObject *path; /* list or None or NULL */
  2026. {
  2027.     extern int fclose Py_PROTO((FILE *));
  2028.     PyObject *fob, *ret;
  2029.     struct filedescr *fdp;
  2030.     char pathname[MAXPATHLEN+1];
  2031.     FILE *fp = NULL;
  2032.  
  2033.     pathname[0] = '\0';
  2034.     if (path == Py_None)
  2035.         path = NULL;
  2036.     fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
  2037.     if (fdp == NULL)
  2038.         return NULL;
  2039.     if (fp != NULL) {
  2040.         fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
  2041.         if (fob == NULL) {
  2042.             fclose(fp);
  2043.             return NULL;
  2044.         }
  2045.     }
  2046.     else {
  2047.         fob = Py_None;
  2048.         Py_INCREF(fob);
  2049.     }        
  2050.     ret = Py_BuildValue("Os(ssi)",
  2051.               fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  2052.     Py_DECREF(fob);
  2053.     return ret;
  2054. }
  2055.  
  2056. static PyObject *
  2057. imp_find_module(self, args)
  2058.     PyObject *self;
  2059.     PyObject *args;
  2060. {
  2061.     char *name;
  2062.     PyObject *path = NULL;
  2063.     if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
  2064.         return NULL;
  2065.     return call_find_module(name, path);
  2066. }
  2067.  
  2068. static PyObject *
  2069. imp_init_builtin(self, args)
  2070.     PyObject *self;
  2071.     PyObject *args;
  2072. {
  2073.     char *name;
  2074.     int ret;
  2075.     PyObject *m;
  2076.     if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
  2077.         return NULL;
  2078.     ret = init_builtin(name);
  2079.     if (ret < 0)
  2080.         return NULL;
  2081.     if (ret == 0) {
  2082.         Py_INCREF(Py_None);
  2083.         return Py_None;
  2084.     }
  2085.     m = PyImport_AddModule(name);
  2086.     Py_XINCREF(m);
  2087.     return m;
  2088. }
  2089.  
  2090. static PyObject *
  2091. imp_init_frozen(self, args)
  2092.     PyObject *self;
  2093.     PyObject *args;
  2094. {
  2095.     char *name;
  2096.     int ret;
  2097.     PyObject *m;
  2098.     if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
  2099.         return NULL;
  2100.     ret = PyImport_ImportFrozenModule(name);
  2101.     if (ret < 0)
  2102.         return NULL;
  2103.     if (ret == 0) {
  2104.         Py_INCREF(Py_None);
  2105.         return Py_None;
  2106.     }
  2107.     m = PyImport_AddModule(name);
  2108.     Py_XINCREF(m);
  2109.     return m;
  2110. }
  2111.  
  2112. static PyObject *
  2113. imp_get_frozen_object(self, args)
  2114.     PyObject *self;
  2115.     PyObject *args;
  2116. {
  2117.     char *name;
  2118.  
  2119.     if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
  2120.         return NULL;
  2121.     return get_frozen_object(name);
  2122. }
  2123.  
  2124. static PyObject *
  2125. imp_is_builtin(self, args)
  2126.     PyObject *self;
  2127.     PyObject *args;
  2128. {
  2129.     char *name;
  2130.     if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
  2131.         return NULL;
  2132.     return PyInt_FromLong(is_builtin(name));
  2133. }
  2134.  
  2135. static PyObject *
  2136. imp_is_frozen(self, args)
  2137.     PyObject *self;
  2138.     PyObject *args;
  2139. {
  2140.     char *name;
  2141.     struct _frozen *p;
  2142.     if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
  2143.         return NULL;
  2144.     p = find_frozen(name);
  2145.     return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
  2146. }
  2147.  
  2148. static FILE *
  2149. get_file(pathname, fob, mode)
  2150.     char *pathname;
  2151.     PyObject *fob;
  2152.     char *mode;
  2153. {
  2154.     FILE *fp;
  2155.     if (fob == NULL) {
  2156.         fp = fopen(pathname, mode);
  2157.         if (fp == NULL)
  2158.             PyErr_SetFromErrno(PyExc_IOError);
  2159.     }
  2160.     else {
  2161.         fp = PyFile_AsFile(fob);
  2162.         if (fp == NULL)
  2163.             PyErr_SetString(PyExc_ValueError,
  2164.                     "bad/closed file object");
  2165.     }
  2166.     return fp;
  2167. }
  2168.  
  2169. static PyObject *
  2170. imp_load_compiled(self, args)
  2171.     PyObject *self;
  2172.     PyObject *args;
  2173. {
  2174.     char *name;
  2175.     char *pathname;
  2176.     PyObject *fob = NULL;
  2177.     PyObject *m;
  2178.     FILE *fp;
  2179.     if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
  2180.                   &PyFile_Type, &fob))
  2181.         return NULL;
  2182.     fp = get_file(pathname, fob, "rb");
  2183.     if (fp == NULL)
  2184.         return NULL;
  2185.     m = load_compiled_module(name, pathname, fp);
  2186.     if (fob == NULL)
  2187.         fclose(fp);
  2188.     return m;
  2189. }
  2190.  
  2191. #ifdef HAVE_DYNAMIC_LOADING
  2192.  
  2193. static PyObject *
  2194. imp_load_dynamic(self, args)
  2195.     PyObject *self;
  2196.     PyObject *args;
  2197. {
  2198.     char *name;
  2199.     char *pathname;
  2200.     PyObject *fob = NULL;
  2201.     PyObject *m;
  2202.     FILE *fp = NULL;
  2203.     if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
  2204.                   &PyFile_Type, &fob))
  2205.         return NULL;
  2206.     if (fob) {
  2207.         fp = get_file(pathname, fob, "r");
  2208.         if (fp == NULL)
  2209.             return NULL;
  2210.     }
  2211.     m = _PyImport_LoadDynamicModule(name, pathname, fp);
  2212.     return m;
  2213. }
  2214.  
  2215. #endif /* HAVE_DYNAMIC_LOADING */
  2216.  
  2217. static PyObject *
  2218. imp_load_source(self, args)
  2219.     PyObject *self;
  2220.     PyObject *args;
  2221. {
  2222.     char *name;
  2223.     char *pathname;
  2224.     PyObject *fob = NULL;
  2225.     PyObject *m;
  2226.     FILE *fp;
  2227.     if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
  2228.                   &PyFile_Type, &fob))
  2229.         return NULL;
  2230.     fp = get_file(pathname, fob, "r");
  2231.     if (fp == NULL)
  2232.         return NULL;
  2233.     m = load_source_module(name, pathname, fp);
  2234.     if (fob == NULL)
  2235.         fclose(fp);
  2236.     return m;
  2237. }
  2238.  
  2239. #ifdef macintosh
  2240. static PyObject *
  2241. imp_load_resource(self, args)
  2242.     PyObject *self;
  2243.     PyObject *args;
  2244. {
  2245.     char *name;
  2246.     char *pathname;
  2247.     PyObject *m;
  2248.  
  2249.     if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
  2250.         return NULL;
  2251.     m = PyMac_LoadResourceModule(name, pathname);
  2252.     return m;
  2253. }
  2254. #endif /* macintosh */
  2255.  
  2256. static PyObject *
  2257. imp_load_module(self, args)
  2258.     PyObject *self;
  2259.     PyObject *args;
  2260. {
  2261.     char *name;
  2262.     PyObject *fob;
  2263.     char *pathname;
  2264.     char *suffix; /* Unused */
  2265.     char *mode;
  2266.     int type;
  2267.     FILE *fp;
  2268.  
  2269.     if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
  2270.                   &name, &fob, &pathname,
  2271.                   &suffix, &mode, &type))
  2272.         return NULL;
  2273.     if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
  2274.         PyErr_Format(PyExc_ValueError,
  2275.                  "invalid file open mode %.200s", mode);
  2276.         return NULL;
  2277.     }
  2278.     if (fob == Py_None)
  2279.         fp = NULL;
  2280.     else {
  2281.         if (!PyFile_Check(fob)) {
  2282.             PyErr_SetString(PyExc_ValueError,
  2283.                 "load_module arg#2 should be a file or None");
  2284.             return NULL;
  2285.         }
  2286.         fp = get_file(pathname, fob, mode);
  2287.         if (fp == NULL)
  2288.             return NULL;
  2289.     }
  2290.     return load_module(name, fp, pathname, type);
  2291. }
  2292.  
  2293. static PyObject *
  2294. imp_load_package(self, args)
  2295.     PyObject *self;
  2296.     PyObject *args;
  2297. {
  2298.     char *name;
  2299.     char *pathname;
  2300.     if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
  2301.         return NULL;
  2302.     return load_package(name, pathname);
  2303. }
  2304.  
  2305. static PyObject *
  2306. imp_new_module(self, args)
  2307.     PyObject *self;
  2308.     PyObject *args;
  2309. {
  2310.     char *name;
  2311.     if (!PyArg_ParseTuple(args, "s:new_module", &name))
  2312.         return NULL;
  2313.     return PyModule_New(name);
  2314. }
  2315.  
  2316. /* Doc strings */
  2317.  
  2318. static char doc_imp[] = "\
  2319. This module provides the components needed to build your own\n\
  2320. __import__ function.  Undocumented functions are obsolete.\n\
  2321. ";
  2322.  
  2323. static char doc_find_module[] = "\
  2324. find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
  2325. Search for a module.  If path is omitted or None, search for a\n\
  2326. built-in, frozen or special module and continue search in sys.path.\n\
  2327. The module name cannot contain '.'; to search for a submodule of a\n\
  2328. package, pass the submodule name and the package's __path__.\
  2329. ";
  2330.  
  2331. static char doc_load_module[] = "\
  2332. load_module(name, file, filename, (suffix, mode, type)) -> module\n\
  2333. Load a module, given information returned by find_module().\n\
  2334. The module name must include the full package name, if any.\
  2335. ";
  2336.  
  2337. static char doc_get_magic[] = "\
  2338. get_magic() -> string\n\
  2339. Return the magic number for .pyc or .pyo files.\
  2340. ";
  2341.  
  2342. static char doc_get_suffixes[] = "\
  2343. get_suffixes() -> [(suffix, mode, type), ...]\n\
  2344. Return a list of (suffix, mode, type) tuples describing the files\n\
  2345. that find_module() looks for.\
  2346. ";
  2347.  
  2348. static char doc_new_module[] = "\
  2349. new_module(name) -> module\n\
  2350. Create a new module.  Do not enter it in sys.modules.\n\
  2351. The module name must include the full package name, if any.\
  2352. ";
  2353.  
  2354. static PyMethodDef imp_methods[] = {
  2355.     {"find_module",        imp_find_module,    1, doc_find_module},
  2356.     {"get_magic",        imp_get_magic,        1, doc_get_magic},
  2357.     {"get_suffixes",    imp_get_suffixes,    1, doc_get_suffixes},
  2358.     {"load_module",        imp_load_module,    1, doc_load_module},
  2359.     {"new_module",        imp_new_module,        1, doc_new_module},
  2360.     /* The rest are obsolete */
  2361.     {"get_frozen_object",    imp_get_frozen_object,    1},
  2362.     {"init_builtin",    imp_init_builtin,    1},
  2363.     {"init_frozen",        imp_init_frozen,    1},
  2364.     {"is_builtin",        imp_is_builtin,        1},
  2365.     {"is_frozen",        imp_is_frozen,        1},
  2366.     {"load_compiled",    imp_load_compiled,    1},
  2367. #ifdef HAVE_DYNAMIC_LOADING
  2368.     {"load_dynamic",    imp_load_dynamic,    1},
  2369. #endif
  2370.     {"load_package",    imp_load_package,    1},
  2371. #ifdef macintosh
  2372.     {"load_resource",    imp_load_resource,    1},
  2373. #endif
  2374.     {"load_source",        imp_load_source,    1},
  2375.     {NULL,            NULL}        /* sentinel */
  2376. };
  2377.  
  2378. static int
  2379. setint(d, name, value)
  2380.     PyObject *d;
  2381.     char *name;
  2382.     int value;
  2383. {
  2384.     PyObject *v;
  2385.     int err;
  2386.  
  2387.     v = PyInt_FromLong((long)value);
  2388.     err = PyDict_SetItemString(d, name, v);
  2389.     Py_XDECREF(v);
  2390.     return err;
  2391. }
  2392.  
  2393. void
  2394. initimp()
  2395. {
  2396.     PyObject *m, *d;
  2397.  
  2398.     m = Py_InitModule4("imp", imp_methods, doc_imp,
  2399.                NULL, PYTHON_API_VERSION);
  2400.     d = PyModule_GetDict(m);
  2401.  
  2402.     if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
  2403.     if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
  2404.     if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
  2405.     if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
  2406.     if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
  2407.     if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
  2408.     if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
  2409.     if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
  2410.     if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
  2411.  
  2412.   failure:
  2413.     ;
  2414. }
  2415.  
  2416.  
  2417. /* API for embedding applications that want to add their own entries
  2418.    to the table of built-in modules.  This should normally be called
  2419.    *before* Py_Initialize().  When the table resize fails, -1 is
  2420.    returned and the existing table is unchanged.
  2421.  
  2422.    After a similar function by Just van Rossum. */
  2423.  
  2424. int
  2425. PyImport_ExtendInittab(newtab)
  2426.     struct _inittab *newtab;
  2427. {
  2428.     static struct _inittab *our_copy = NULL;
  2429.     struct _inittab *p;
  2430.     int i, n;
  2431.  
  2432.     /* Count the number of entries in both tables */
  2433.     for (n = 0; newtab[n].name != NULL; n++)
  2434.         ;
  2435.     if (n == 0)
  2436.         return 0; /* Nothing to do */
  2437.     for (i = 0; PyImport_Inittab[i].name != NULL; i++)
  2438.         ;
  2439.  
  2440.     /* Allocate new memory for the combined table */
  2441.     p = our_copy;
  2442.     PyMem_RESIZE(p, struct _inittab, i+n+1);
  2443.     if (p == NULL)
  2444.         return -1;
  2445.  
  2446.     /* Copy the tables into the new memory */
  2447.     if (our_copy != PyImport_Inittab)
  2448.         memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
  2449.     PyImport_Inittab = our_copy = p;
  2450.     memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
  2451.  
  2452.     return 0;
  2453. }
  2454.  
  2455. /* Shorthand to add a single entry given a name and a function */
  2456.  
  2457. int
  2458. PyImport_AppendInittab(name, initfunc)
  2459.     char *name;
  2460.     void (*initfunc)();
  2461. {
  2462.     struct _inittab newtab[2];
  2463.  
  2464.     memset(newtab, '\0', sizeof newtab);
  2465.  
  2466.     newtab[0].name = name;
  2467.     newtab[0].initfunc = initfunc;
  2468.  
  2469.     return PyImport_ExtendInittab(newtab);
  2470. }
  2471.